package com.betterjr.modules.application.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.modules.application.IAmsMenuInfoUndercarriage;
import com.betterjr.modules.application.dao.AmsMenuResourceRelationMapper;
import com.betterjr.modules.application.data.AmsMenuResourceRelationConstantCollections;
import com.betterjr.modules.application.entity.AmsMenuResourceRelation;
import com.betterjr.modules.application.entity.AmsResource;

/**
 * 
 * @ClassName: AmsMenuResourceRelationService 
 * @Description: 菜单资源关系表服务 
 * @author xuyp
 * @date 2017年11月17日 下午6:05:27 
 *
 */
@Service
public class AmsMenuResourceRelationService extends BaseService<AmsMenuResourceRelationMapper, AmsMenuResourceRelation>
        implements IAmsMenuInfoUndercarriage {

    @Autowired
    private AmsResourceService resourceService;

    /**
     * 
     * @Title: selectResourcesByMenuInfoId 
     * @Description: 查询菜单的所有资源信息
     * @param anMenuId  菜单id
     * @return List<AmsResource> 资源集合
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午11:43:19
     */
    @SuppressWarnings("unchecked")
    public List<AmsResource> selectResourcesByMenuInfoId(Long anMenuId) {

        Map<String, Object> map = QueryTermBuilder.newInstance().put("menuId", anMenuId)
                .put("businStatus",
                        AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_EFFECTIVE)
                .build();

        List<AmsMenuResourceRelation> list = this.selectByProperty(map);
        if (Collections3.isEmpty(list)) {
            return new ArrayList<AmsResource>();
        }

        List<AmsResource> resourceList = new ArrayList<AmsResource>(list.size());
        for (AmsMenuResourceRelation relation : list) {
            resourceList.add(resourceService.selectByPrimaryKey(relation.getResourceId()));
        }

        return resourceList;
    }

    /**
     * 
     * @Title: updateRelationsByMenuinfoIdWithResourceIds 
     * @Description: 更新菜单资源表信息
     * @param anMenuInfoId  菜单id
     * @param anRourceIds   资源id集合
     * @return List<AmsMenuResourceRelation>
     * @throws 
     * @author xuyp
     * @date 2017年11月17日 下午5:49:16
     */
    @SuppressWarnings("unchecked")
    public List<AmsMenuResourceRelation> updateRelationsByMenuinfoIdWithResourceIds(Long anMenuInfoId,
            String anRourceIds) {
        BTAssert.notNull(anMenuInfoId, "数据为空,操作失败");

        Map<String, Object> map = QueryTermBuilder.newInstance().put("menuId", anMenuInfoId)
                .put("businStatus",
                        AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_EFFECTIVE)
                .build();

        List<AmsMenuResourceRelation> list = this.selectByProperty(map);
        if (Collections3.isEmpty(list)) {
            // 插入关系表
            return saveInsertRelations(anMenuInfoId, anRourceIds);

        } else {
            // 更新关系表
            StringBuilder sb = new StringBuilder();
            for (AmsMenuResourceRelation amsMenuResourceRelation : list) {
                sb.append(amsMenuResourceRelation.getResourceId()).append(",");
            }
            return saveInsertOrModifyRelations(anMenuInfoId, anRourceIds, sb.toString());
        }

        // return null;
    }

    /**
     * 
     * @Title: saveInsertOrModifyRelations 
     * @Description: 更新或者插入关系表信息 
     * @param anMenuInfoId 菜单id
     * @param anRourceIds 需要插入到数据库的资源id集合
     * @param anOldResourceIds  原来在数据库中已经存在的资源id集合
     * @return 返回新插入的资源关系表集合
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午9:43:42
     */
    private List<AmsMenuResourceRelation> saveInsertOrModifyRelations(Long anMenuInfoId, String anRourceIds,
            String anOldResourceIds) {

        String okResourceIds = findDifferencesResources(anRourceIds, anOldResourceIds, "1");

        String errorResourceIds = findDifferencesResources(anRourceIds, anOldResourceIds, "9");

        // 插入新的资源信息
        List<AmsMenuResourceRelation> list = saveInsertRelations(anMenuInfoId, okResourceIds);

        // 修改已经有的资源信息变成不生效
        saveRelationsNoEffective(anMenuInfoId, errorResourceIds);

        return list;
    }

    /**
     * 
     * @Title: saveRelationsNoEffective 
     * @Description: 将生效的设置成不生效
     * @param anMenuInfoId
     * @param anErrorResourceIds 即将失效的id集合
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午10:25:47
     */
    @SuppressWarnings("unchecked")
    private List<AmsMenuResourceRelation> saveRelationsNoEffective(Long anMenuInfoId, String anErrorResourceIds) {

        if (StringUtils.isNoneBlank(anErrorResourceIds)) {

            List<String> list = Arrays.asList(anErrorResourceIds.split(","));
            List<Long> longList = new ArrayList<>(list.size());
            for (String str : list) {

                try {
                    longList.add(Long.parseLong(str));
                }
                catch (Exception e) {

                }

            }

            if (!Collections3.isEmpty(longList)) {

                Map<String, Object> map = QueryTermBuilder.newInstance().put("menuId", anMenuInfoId)
                        .put("resourceId", longList)
                        .put("businStatus",
                                AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_EFFECTIVE)
                        .build();
                List<AmsMenuResourceRelation> relationList = this.selectByProperty(map);
                for (AmsMenuResourceRelation relation : relationList) {
                    relation.setBusinStatus(
                            AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_NOEFFECTIVE);
                    this.updateByPrimaryKeySelective(relation);
                }

                return relationList;

            }

        }

        return null;

    }

    /**
     * 
     * @Title: findDifferencesResources 
     * @Description: 遍历两个资源的不同
     * @param anRourceIds  需要插入到数据库的资源id集合
     * @param anOldResourceIds  原来在数据库中已经存在的资源id集合
     * @param flag  1 得到需要插入的字符串   9得到需要删除的字符串
     * @return 资源id,资源id,资源id,资源id,资源id
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午9:48:46
     */
    private String findDifferencesResources(String anRourceIds, String anOldResourceIds, String flag) {

        StringBuilder okSb = new StringBuilder();
        StringBuilder errorSb = new StringBuilder();
        if (StringUtils.isBlank(anRourceIds)) {
            if (AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_EFFECTIVE.equals(flag)) {
                return okSb.toString();
            } else {
                return anOldResourceIds;
            }
        }

        List<String> resourceIds = Arrays.asList(anRourceIds.split(","));
        List<String> oldResourceIds = Arrays.asList(anOldResourceIds.split(","));
        for (String resourceId : resourceIds) {
            if (!oldResourceIds.contains(resourceId)) {
                okSb.append(resourceId).append(",");
            }
        }

        for (String oldResourceId : oldResourceIds) {
            if (!resourceIds.contains(oldResourceId)) {
                errorSb.append(oldResourceId).append(",");
            }
        }

        if (AmsMenuResourceRelationConstantCollections.AMSMENURESOURCERELATION_BUSINSTATUS_EFFECTIVE.equals(flag)) {
            return okSb.toString();
        } else {
            return errorSb.toString();
        }

    }

    /**
     * 
     * @Title: saveInsertRelation 
     * @Description: 插入菜单资源关系表
     * @param anMenuInfoId  菜单id
     * @param anRourceIds   资源id,资源id,资源id,资源id
     * @return 返回插入到数据库的资源关系列表信息
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午9:02:02
     */
    private List<AmsMenuResourceRelation> saveInsertRelations(Long anMenuInfoId, String anRourceIds) {

        List<AmsMenuResourceRelation> relations = new ArrayList<>();
        if (StringUtils.isNoneBlank(anRourceIds)) {
            if (anRourceIds.contains(",")) {
                for (String resourceId : anRourceIds.split(",")) {
                    relations.add(saveInsertRelation(anMenuInfoId, resourceId));
                }
            } else {
                relations.add(saveInsertRelation(anMenuInfoId, anRourceIds));
            }
        }

        return relations;
    }

    /**
     * 
     * @Title: saveInsertRelation 
     * @Description: 插入菜单资源关系表 
     * @param anMenuInfoId 菜单id
     * @param anRourceIds  资源id
     * @return 返回插入到数据库的资源关系列表信息
     * @throws 
     * @author xuyp
     * @date 2017年11月20日 上午9:07:02
     */
    private AmsMenuResourceRelation saveInsertRelation(Long anMenuInfoId, String anRourceIds) {

        AmsMenuResourceRelation relation = new AmsMenuResourceRelation();

        relation.saveAddValue();
        relation.setMenuId(anMenuInfoId);
        try {
            Long resourceId = Long.parseLong(anRourceIds);
            relation.setResourceId(resourceId);
            this.insertSelective(relation);
            return relation;
        }
        catch (Exception e) {
            logger.info("新增菜单资源关系失败！" + e.getMessage());
        }

        return null;
    }

    /**
     * 
     * <p>Overriding Method of saveUndercarriageMenuInfo</p>  
     * <p>Description: </p> 
     * @param anMenuId  菜单id
     * @see com.betterjr.modules.application.IAmsMenuInfoUndercarriage#saveUndercarriageMenuInfo(java.lang.Long) 
     * @author xuyp
     * @date 2017年12月21日 下午3:14:59
     */
    @Override
    public void saveUndercarriageMenuInfo(Long anMenuId) {

        if (anMenuId != null) {

            this.mapper.updateBusinStatusToNoEffective(anMenuId);

        }

    }

}
